package com.eastfair.venuebooking.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.auth.api.UserAccountServiceFeign;
import com.eastfair.auth.vo.UserAccountVo;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.common.dto.AttachmentFileDTO;
import com.eastfair.common.vo.AttachmentFileVO;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.messagecenter.api.MsgServiceFeign;
import com.eastfair.messagecenter.util.SendMsgUtil;
import com.eastfair.messagecenter.util.SmsSendDtoUtil;
import com.eastfair.pay.api.AttachmentFileFeign;
import com.eastfair.venuebooking.dao.ExhibitionTaskMapper;
import com.eastfair.venuebooking.dto.ExhibitionTaskDTO;
import com.eastfair.venuebooking.dto.ExhibitionTaskOrgDTO;
import com.eastfair.venuebooking.dto.ExhibitionTaskQuery;
import com.eastfair.venuebooking.entity.*;
import com.eastfair.venuebooking.enumeration.ExhibitionTaskFinishStatusEnum;
import com.eastfair.venuebooking.enums.FollowRemindWayEnum;
import com.eastfair.venuebooking.enums.VenueBookingMoudleEnum;
import com.eastfair.venuebooking.exceptioncode.VenueBookingExceptionCode;
import com.eastfair.venuebooking.service.*;
import com.eastfair.venuebooking.vo.*;
import com.eastfair.venueservice.consts.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 任务
 * </p>
 *
 * @author linan
 * @date 2022-06-08
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class ExhibitionTaskServiceImpl extends SuperServiceImpl<ExhibitionTaskMapper, ExhibitionTask> implements ExhibitionTaskService {

    @Resource
    private ExhibitionTaskOrgService exhibitionTaskOrgService;
    @Resource
    private ExhibitionSegmentService exhibitionSegmentService;
    @Resource
    private ExhibitionResponsibilityerService exhibitionResponsibilityerService;
    @Resource
    private SpaceService spaceService;
    @Resource
    private AttachmentFileFeign attachmentFileFeign;
    @Resource
    private ExhibitionService exhibitionService;

    @Resource(name = "threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private SendMsgUtil sendMsgUtil;

    @Resource
    private MsgServiceFeign msgServiceFeign;
    @Resource
    private UserAccountServiceFeign userAccountServiceFeign;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<ExhibitionTask> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(ExhibitionTask model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTenantId(ContextUtil.getTenantId());
        //雪花ID
        return R.successDef();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addExhibitionTask(ExhibitionTaskDTO exhibitionSaveDTO) {
        ExhibitionTask exhibitionTask = new ExhibitionTask();
        BeanUtils.copyProperties(exhibitionSaveDTO,exhibitionTask);
        dealSpace(exhibitionTask, exhibitionSaveDTO.getSpaceList());
        exhibitionTask.setFinishStatus(ExhibitionTaskFinishStatusEnum.NOT_FINISHED);
        save(exhibitionTask);
        Long exhibitionId = exhibitionSaveDTO.getExhibitionId();
        Exhibition exhibition = exhibitionService.getById(exhibitionId);
        String exhibitionName = Objects.nonNull(exhibition) ?exhibition.getExhibitionName():Strings.EMPTY;
        for (ExhibitionTaskOrgDTO exhibitionTaskOrgSaveDTO : exhibitionSaveDTO.getExhibitionTaskOrg()) {
            ExhibitionTaskOrg exhibitionTaskOrg = new ExhibitionTaskOrg();
            BeanUtils.copyProperties(exhibitionTaskOrgSaveDTO,exhibitionTaskOrg);
            exhibitionTaskOrg.setTaskId(exhibitionTask.getId());
            exhibitionTaskOrg.setRemindWay(exhibitionSaveDTO.getRemindWay());
            exhibitionTaskOrgService.save(exhibitionTaskOrg);
            if(StringUtils.isNotBlank(exhibitionSaveDTO.getRemindWay())){
                threadPoolTaskExecutor.execute(()->{
                    for (String remindWay : exhibitionSaveDTO.getRemindWay().split(StringPool.COMMA)) {
                        String content;
                        if (StringUtils.isBlank(exhibitionTask.getTaskName())) {
                            content = String.format("%s新建任务%s，请及时处理！", exhibitionName, exhibitionTask.getTaskName());
                        } else {
                            content = String.format("%s新建任务%s，任务描述：%s，请及时处理！", exhibitionName, exhibitionTask.getTaskName(), exhibitionTask.getRemark());
                        }
                        // 发送站内信
                        if (FollowRemindWayEnum.SYS_MESSAGE.getCode().equals(remindWay)) {
                            sendTaskInnerMsg(exhibitionTaskOrgSaveDTO,content);
                        }
                        // 发送短信
                        if (FollowRemindWayEnum.SHORT_MESSAGE.getCode().equals(remindWay)) {
                            sendTaskSmsMsg(exhibitionTaskOrgSaveDTO,content);
                        }
                    }
                });
            }
        }
        // 修改环节为不可删除
        exhibitionSegmentService.updateDeleteAble(exhibitionSaveDTO.getSegmentId(),false);
        return exhibitionTask.getId();
    }

    private void sendTaskSmsMsg(ExhibitionTaskOrgDTO exhibitionTaskOrgSaveDTO,String content) {
        Long responsibleUserId = exhibitionTaskOrgSaveDTO.getResponsibleUserId();
        R<UserAccountVo> simpleById = userAccountServiceFeign.findSimpleById(responsibleUserId);
        String mobile = simpleById.getData().getMobile();
        Set<String> nums =new HashSet<>(8);
        nums.add(mobile);
        msgServiceFeign.sendSmsMsg(SmsSendDtoUtil.sendSmsDto(CommonConstants.BUSINESS_COMMON, nums, content));
    }

    private void sendTaskInnerMsg(ExhibitionTaskOrgDTO exhibitionTaskOrgSaveDTO,String content) {
        Long responsibleUserId = exhibitionTaskOrgSaveDTO.getResponsibleUserId();
        sendMsgUtil.sendInnerMsgByUserId(content,responsibleUserId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateExhibitionTask(ExhibitionTaskDTO exhibitionUpdateDTO) {
        // 查询原信息
        ExhibitionTask oldExhibition = this.getById(exhibitionUpdateDTO.getId());
        ExhibitionTask exhibitionTask = new ExhibitionTask();
        BeanUtils.copyProperties(exhibitionUpdateDTO,exhibitionTask);
        exhibitionTask.setId(exhibitionUpdateDTO.getId());
        List<ExhibitionTaskDTO.ExhibitionTaskSpaceDTO> spaceList = exhibitionUpdateDTO.getSpaceList();
        dealSpace(exhibitionTask, spaceList);
        boolean b = updateById(exhibitionTask);
        Long exhibitionId = oldExhibition.getExhibitionId();
        Exhibition exhibition = exhibitionService.getById(exhibitionId);
        String exhibitionName = Objects.nonNull(exhibition) ?exhibition.getExhibitionName():Strings.EMPTY;
        // 重新生成部门/任务关系
        UpdateWrapper<ExhibitionTaskOrg> rq = new UpdateWrapper<>();
        rq.lambda().eq(ExhibitionTaskOrg::getTaskId,exhibitionUpdateDTO.getId()).eq(ExhibitionTaskOrg::getIsDeleted,BusinessConstant.NO).set(ExhibitionTaskOrg::getIsDeleted,BusinessConstant.YES);
        exhibitionTaskOrgService.update(rq);
        for (ExhibitionTaskOrgDTO exhibitionTaskOrgUpdateDTO : exhibitionUpdateDTO.getExhibitionTaskOrg()) {
            ExhibitionTaskOrg exhibitionTaskOrg = new ExhibitionTaskOrg();
            BeanUtils.copyProperties(exhibitionTaskOrgUpdateDTO,exhibitionTaskOrg);
            exhibitionTaskOrg.setTaskId(exhibitionTask.getId());
            exhibitionTaskOrg.setRemindWay(exhibitionUpdateDTO.getRemindWay());
            exhibitionTaskOrgService.save(exhibitionTaskOrg);
            if(StringUtils.isNotBlank(exhibitionTaskOrg.getRemindWay())){
                threadPoolTaskExecutor.execute(()->{
                    for (String remindWay : exhibitionTaskOrg.getRemindWay().split(StringPool.COMMA)) {
                        String content;
                        if (StringUtils.isBlank(exhibitionTask.getTaskName())) {
                            content = String.format("%s,%s，任务内容有修改，请及时处理！", exhibitionName, exhibitionTask.getTaskName());
                        } else {
                            content = String.format("%s,%s，任务描述：%s，任务内容有修改，请及时处理！", exhibitionName, exhibitionTask.getTaskName(), exhibitionTask.getRemark());
                        }
                        // 发送站内信
                        if (FollowRemindWayEnum.SYS_MESSAGE.getCode().equals(remindWay)) {
                            sendTaskInnerMsg(exhibitionTaskOrgUpdateDTO,content);
                        }
                        // 发送短信
                        if (FollowRemindWayEnum.SHORT_MESSAGE.getCode().equals(remindWay)) {
                            sendTaskSmsMsg(exhibitionTaskOrgUpdateDTO,content);
                        }
                    }
                });
            }
        }
        // 修改该环节为不可删除
        exhibitionSegmentService.updateDeleteAble(exhibitionUpdateDTO.getSegmentId(),false);
        // 修改原绑定环节id的是否可删除状态
        exhibitionSegmentService.updateDeleteAble(oldExhibition);
        return b;
    }

    private void dealSpace(ExhibitionTask exhibitionTask, List<ExhibitionTaskDTO.ExhibitionTaskSpaceDTO> spaceList2) {
        StringBuilder spaceIdSb = new StringBuilder();
        StringBuilder spaceNameSb = new StringBuilder();

        for (ExhibitionTaskDTO.ExhibitionTaskSpaceDTO exhibitionTaskSpaceSaveDTO : spaceList2) {
            spaceIdSb.append(exhibitionTaskSpaceSaveDTO.getSpaceId()).append(BusinessConstant.COMMA);
            spaceNameSb.append(exhibitionTaskSpaceSaveDTO.getSpaceName()).append(BusinessConstant.COMMA);
        }
        if (spaceIdSb.length() > 0) {
            spaceIdSb.deleteCharAt(spaceIdSb.length() - 1);
            exhibitionTask.setSpaceId(spaceIdSb.toString());
        }
        if (spaceNameSb.length() > 0) {
            spaceNameSb.deleteCharAt(spaceNameSb.length() - 1);
            exhibitionTask.setSpaceName(spaceNameSb.length() > 1024 ? spaceNameSb.substring(0, 1024) : spaceNameSb.toString());
        }
    }



    /**
     * 通过展会环节导出任务书
     * @param response response
     * @param exhibition exhibition
     * @throws IOException IOException
     */
    @Override
    public void exportBySegment(HttpServletResponse response, Exhibition exhibition) throws IOException {
        // 查询展会环节
        QueryWrapper<ExhibitionSegment> exhibitionSegmentQueryWrapper = new QueryWrapper<>();
        exhibitionSegmentQueryWrapper.lambda().eq(ExhibitionSegment::getExhibitionId, exhibition.getId()).eq(ExhibitionSegment::getIsDeleted, BusinessConstant.NO);
        // 导出对象
        ArrayList<ExhibitionTaskExportVO> exhibitionTaskExportVOS = new ArrayList<>();
        for (ExhibitionSegment exhibitionSegment : exhibitionSegmentService.list(exhibitionSegmentQueryWrapper)) {
            ExhibitionTaskExportVO exhibitionTaskExportVO = new ExhibitionTaskExportVO();
            List<ExhibitionTaskExportVO.ExhibitionTaskExportDetailVO> exhibitionTaskExportDetailVOS = new ArrayList<>();
            // 环节对应任务
            QueryWrapper<ExhibitionTask> exhibitionTaskQueryWrapper = new QueryWrapper<>();
            exhibitionTaskQueryWrapper.lambda().eq(ExhibitionTask::getSegmentId,exhibitionSegment.getId()).eq(ExhibitionTask::getIsDeleted,BusinessConstant.NO);
            List<ExhibitionTask> list = list(exhibitionTaskQueryWrapper);
            for (ExhibitionTask exhibitionTask : list) {
                List<String> spaceNameList = new ArrayList<>();
                // 获取展厅
                if(StringUtils.isNotBlank(exhibitionTask.getSpaceId())){
                    for (String s : exhibitionTask.getSpaceId().split(BusinessConstant.COMMA)) {
                        long spaceId = Long.parseLong(s);
                        Space space = spaceService.getById(spaceId);
                        if(Objects.nonNull(space)){
                            // 获取展厅名称
                            spaceNameList.add(space.getSpaceName());
                        }
                    }
                }
                // 获取部门
                QueryWrapper<ExhibitionTaskOrg> exhibitionTaskOrgQueryWrapper = new QueryWrapper<>();
                exhibitionTaskOrgQueryWrapper.lambda().eq(ExhibitionTaskOrg::getTaskId,exhibitionTask.getId()).eq(ExhibitionTaskOrg::getIsDeleted,BusinessConstant.NO);
                List<ExhibitionTaskOrg> exhibitionTaskOrgs = exhibitionTaskOrgService.list(exhibitionTaskOrgQueryWrapper);
                // 如果找不到展会部门和展厅的特殊处理
                if(CollectionUtils.isEmpty(spaceNameList)){
                    spaceNameList.add(Strings.EMPTY);
                }
                if(CollectionUtils.isEmpty(exhibitionTaskOrgs)){
                    ExhibitionTaskOrg exhibitionTaskOrg = new ExhibitionTaskOrg();
                    exhibitionTaskOrg.setOrgName(Strings.EMPTY);
                    exhibitionTaskOrgs.add(exhibitionTaskOrg);
                }
                for (String spaceName : spaceNameList) {
                    for (ExhibitionTaskOrg org : exhibitionTaskOrgs) {
                        ExhibitionTaskExportVO.ExhibitionTaskExportDetailVO exhibitionTaskExportDetailVO = new ExhibitionTaskExportVO.ExhibitionTaskExportDetailVO();
                        // 任务标题
                        exhibitionTaskExportDetailVO.setTaskName(exhibitionTask.getTaskName());
                        // 服务部门
                        exhibitionTaskExportDetailVO.setOrgName(org.getOrgName());
                        // 场地名称
                        exhibitionTaskExportDetailVO.setSpaceName(spaceName);
                        // 开始时间
                        exhibitionTaskExportDetailVO.setStartDate(exhibitionTask.getStartTime().toLocalDate().toString());
                        // 结束时间
                        exhibitionTaskExportDetailVO.setEndDate(exhibitionTask.getEndTime().toLocalDate().toString());
                        // 完成状态
                        exhibitionTaskExportDetailVO.setFinishStatusName(exhibitionTask.getFinishStatus().getDesc());
                        // 主要负责人
                        exhibitionTaskExportDetailVO.setName(org.getResponsibleUserName());
                        exhibitionTaskExportDetailVOS.add(exhibitionTaskExportDetailVO);
                    }
                }
            }
            if(CollectionUtils.isNotEmpty(list)){
                // 环节名称
                exhibitionTaskExportVO.setSegmentName(exhibitionSegment.getSegmentName());
                exhibitionTaskExportVO.setExhibitionTaskExportDetailVO(exhibitionTaskExportDetailVOS);
                exhibitionTaskExportVOS.add(exhibitionTaskExportVO);
            }
        }
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("任务书", "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        ExportParams exportParams = new ExportParams();
        exportParams.setTitle(exhibition.getExhibitionName());
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ExhibitionTaskExportVO.class, exhibitionTaskExportVOS);
        workbook.write(response.getOutputStream());
    }

    @Override
    public void exportByOrg(HttpServletResponse response, Exhibition exhibition) throws IOException {
        // 查询展会环节
        QueryWrapper<ExhibitionSegment> exhibitionSegmentQueryWrapper = new QueryWrapper<>();
        exhibitionSegmentQueryWrapper.lambda().eq(ExhibitionSegment::getExhibitionId, exhibition.getId()).eq(ExhibitionSegment::getIsDeleted, BusinessConstant.NO);
        // 导出对象
        ArrayList<ExhibitionTaskExportByOrgVO> exhibitionTaskExportByOrgVOS = new ArrayList<>();
        Map<String, List<ExhibitionTaskExportByOrgVO.ExhibitionTaskExportDetailVO>> map = new HashMap<>(8);
        for (ExhibitionSegment exhibitionSegment : exhibitionSegmentService.list(exhibitionSegmentQueryWrapper)) {
            // 环节对应任务
            QueryWrapper<ExhibitionTask> exhibitionTaskQueryWrapper = new QueryWrapper<>();
            exhibitionTaskQueryWrapper.lambda().eq(ExhibitionTask::getSegmentId,exhibitionSegment.getId()).eq(ExhibitionTask::getIsDeleted,BusinessConstant.NO);
            for (ExhibitionTask exhibitionTask : list(exhibitionTaskQueryWrapper)) {
                List<String> spaceNameList = new ArrayList<>();
                // 获取展厅
                if(StringUtils.isNotBlank(exhibitionTask.getSpaceId())){
                    for (String s : exhibitionTask.getSpaceId().split(BusinessConstant.COMMA)) {
                        long spaceId = Long.parseLong(s);
                        Space space = spaceService.getById(spaceId);
                        if(Objects.nonNull(space)){
                            // 获取展厅名称
                            spaceNameList.add(space.getSpaceName());
                        }
                    }
                }
                // 获取部门
                QueryWrapper<ExhibitionTaskOrg> exhibitionTaskOrgQueryWrapper = new QueryWrapper<>();
                exhibitionTaskOrgQueryWrapper.lambda().eq(ExhibitionTaskOrg::getTaskId,exhibitionTask.getId()).eq(ExhibitionTaskOrg::getIsDeleted,BusinessConstant.NO);
                List<ExhibitionTaskOrg> exhibitionTaskOrgs = exhibitionTaskOrgService.list(exhibitionTaskOrgQueryWrapper);
                // 如果找不到展会部门和展厅的特殊处理
                if(CollectionUtils.isEmpty(spaceNameList)){
                    spaceNameList.add(Strings.EMPTY);
                }
                if(CollectionUtils.isEmpty(exhibitionTaskOrgs)){
                    ExhibitionTaskOrg exhibitionTaskOrg = new ExhibitionTaskOrg();
                    exhibitionTaskOrg.setOrgName(Strings.EMPTY);
                    exhibitionTaskOrgs.add(exhibitionTaskOrg);
                }
                for (String spaceName : spaceNameList) {
                    for (ExhibitionTaskOrg org : exhibitionTaskOrgs) {
                        ExhibitionTaskExportByOrgVO.ExhibitionTaskExportDetailVO exhibitionTaskExportDetailVO = new ExhibitionTaskExportByOrgVO.ExhibitionTaskExportDetailVO();
                        // 任务标题
                        exhibitionTaskExportDetailVO.setTaskName(exhibitionTask.getTaskName());
                        // 服务部门
                        exhibitionTaskExportDetailVO.setSegmentName(exhibitionSegment.getSegmentName());
                        // 场地名称
                        exhibitionTaskExportDetailVO.setSpaceName(spaceName);
                        // 开始时间
                        exhibitionTaskExportDetailVO.setStartDate(exhibitionTask.getStartTime().toLocalDate().toString());
                        // 结束时间
                        exhibitionTaskExportDetailVO.setEndDate(exhibitionTask.getEndTime().toLocalDate().toString());
                        // 完成状态
                        exhibitionTaskExportDetailVO.setFinishStatusName(exhibitionTask.getFinishStatus().getDesc());
                        // 主要负责人
                        exhibitionTaskExportDetailVO.setName(org.getResponsibleUserName());
                        List<ExhibitionTaskExportByOrgVO.ExhibitionTaskExportDetailVO> exhibitionTaskExportDetailVOS = map.get(org.getOrgName());
                        if(CollectionUtils.isEmpty(exhibitionTaskExportDetailVOS)){
                            List<ExhibitionTaskExportByOrgVO.ExhibitionTaskExportDetailVO> detailVOS = new ArrayList<>();
                            detailVOS.add(exhibitionTaskExportDetailVO);
                            map.put(org.getOrgName(), detailVOS);
                        }else {
                            exhibitionTaskExportDetailVOS.add(exhibitionTaskExportDetailVO);
                        }
                    }
                }
            }
        }
        map.forEach((orgName,entity)->{
            ExhibitionTaskExportByOrgVO exhibitionTaskExportByOrgVO = new ExhibitionTaskExportByOrgVO();
            exhibitionTaskExportByOrgVO.setOrgName(orgName);
            exhibitionTaskExportByOrgVO.setExhibitionTaskExportDetailVO(entity);
            exhibitionTaskExportByOrgVOS.add(exhibitionTaskExportByOrgVO);
        });
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("任务书", "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        ExportParams exportParams = new ExportParams();
        exportParams.setTitle(exhibition.getExhibitionName());
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ExhibitionTaskExportByOrgVO.class, exhibitionTaskExportByOrgVOS);
        workbook.write(response.getOutputStream());

    }

    @Override
    public void exportBySpace(HttpServletResponse response, Exhibition exhibition) throws IOException {
        // 查询展会环节
        QueryWrapper<ExhibitionSegment> exhibitionSegmentQueryWrapper = new QueryWrapper<>();
        exhibitionSegmentQueryWrapper.lambda().eq(ExhibitionSegment::getExhibitionId, exhibition.getId()).eq(ExhibitionSegment::getIsDeleted, BusinessConstant.NO);
        // 导出对象
        ArrayList<ExhibitionTaskExportBySpaceVO> exhibitionTaskExportBySpaceVOS = new ArrayList<>();
        Map<String, List<ExhibitionTaskExportBySpaceVO.ExhibitionTaskExportDetailVO>> map = new HashMap<>(8);
        for (ExhibitionSegment exhibitionSegment : exhibitionSegmentService.list(exhibitionSegmentQueryWrapper)) {
            // 环节对应任务
            QueryWrapper<ExhibitionTask> exhibitionTaskQueryWrapper = new QueryWrapper<>();
            exhibitionTaskQueryWrapper.lambda().eq(ExhibitionTask::getSegmentId,exhibitionSegment.getId()).eq(ExhibitionTask::getIsDeleted,BusinessConstant.NO);
            for (ExhibitionTask exhibitionTask : list(exhibitionTaskQueryWrapper)) {
                List<String> spaceNameList = new ArrayList<>();
                // 获取展厅
                if(StringUtils.isNotBlank(exhibitionTask.getSpaceId())){
                    for (String s : exhibitionTask.getSpaceId().split(BusinessConstant.COMMA)) {
                        long spaceId = Long.parseLong(s);
                        Space space = spaceService.getById(spaceId);
                        if(Objects.nonNull(space)){
                            // 获取展厅名称
                            spaceNameList.add(space.getSpaceName());
                        }
                    }
                }
                // 获取部门
                QueryWrapper<ExhibitionTaskOrg> exhibitionTaskOrgQueryWrapper = new QueryWrapper<>();
                exhibitionTaskOrgQueryWrapper.lambda().eq(ExhibitionTaskOrg::getTaskId,exhibitionTask.getId()).eq(ExhibitionTaskOrg::getIsDeleted,BusinessConstant.NO);
                List<ExhibitionTaskOrg> exhibitionTaskOrgs = exhibitionTaskOrgService.list(exhibitionTaskOrgQueryWrapper);
                // 如果找不到展会部门和展厅的特殊处理
                if(CollectionUtils.isEmpty(spaceNameList)){
                    spaceNameList.add(Strings.EMPTY);
                }
                if(CollectionUtils.isEmpty(exhibitionTaskOrgs)){
                    ExhibitionTaskOrg exhibitionTaskOrg = new ExhibitionTaskOrg();
                    exhibitionTaskOrg.setOrgName(Strings.EMPTY);
                    exhibitionTaskOrgs.add(exhibitionTaskOrg);
                }
                for (String spaceName : spaceNameList) {
                    for (ExhibitionTaskOrg org : exhibitionTaskOrgs) {
                        ExhibitionTaskExportBySpaceVO.ExhibitionTaskExportDetailVO exhibitionTaskExportDetailVO = new ExhibitionTaskExportBySpaceVO.ExhibitionTaskExportDetailVO();
                        // 任务标题
                        exhibitionTaskExportDetailVO.setTaskName(exhibitionTask.getTaskName());
                        // 环节
                        exhibitionTaskExportDetailVO.setSegmentName(exhibitionSegment.getSegmentName());
                        // 服务部门
                        exhibitionTaskExportDetailVO.setOrgName(org.getOrgName());
                        // 开始时间
                        exhibitionTaskExportDetailVO.setStartDate(exhibitionTask.getStartTime().toLocalDate().toString());
                        // 结束时间
                        exhibitionTaskExportDetailVO.setEndDate(exhibitionTask.getEndTime().toLocalDate().toString());
                        // 完成状态
                        exhibitionTaskExportDetailVO.setFinishStatusName(exhibitionTask.getFinishStatus().getDesc());
                        // 主要负责人
                        exhibitionTaskExportDetailVO.setName(org.getResponsibleUserName());
                        List<ExhibitionTaskExportBySpaceVO.ExhibitionTaskExportDetailVO> exhibitionTaskExportDetailVOS = map.get(spaceName);
                        if(CollectionUtils.isEmpty(exhibitionTaskExportDetailVOS)){
                            List<ExhibitionTaskExportBySpaceVO.ExhibitionTaskExportDetailVO> detailVOS = new ArrayList<>();
                            detailVOS.add(exhibitionTaskExportDetailVO);
                            map.put(spaceName, detailVOS);
                        }else {
                            exhibitionTaskExportDetailVOS.add(exhibitionTaskExportDetailVO);
                        }
                    }
                }
            }
        }
        map.forEach((spaceName,entity)->{
            ExhibitionTaskExportBySpaceVO exhibitionTaskExportBySpaceVO = new ExhibitionTaskExportBySpaceVO();
            exhibitionTaskExportBySpaceVO.setSpaceName(spaceName);
            exhibitionTaskExportBySpaceVO.setExhibitionTaskExportDetailVO(entity);
            exhibitionTaskExportBySpaceVOS.add(exhibitionTaskExportBySpaceVO);
        });
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("任务书"+ LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")), "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        ExportParams exportParams = new ExportParams();
        exportParams.setTitle(exhibition.getExhibitionName());
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ExhibitionTaskExportBySpaceVO.class, exhibitionTaskExportBySpaceVOS);
        workbook.write(response.getOutputStream());

    }

    @Override
    public IPage<ExhibitionTaskVO> queryExhibitionTaskList(PageParams<ExhibitionTaskQuery> params) {
        ExhibitionTaskQuery model = params.getModel();
        QueryWrapper<ExhibitionTask> exhibitionTaskPageQueryQueryWrapper = new QueryWrapper<>();
        exhibitionTaskPageQueryQueryWrapper.lambda()
                .eq(ExhibitionTask::getExhibitionId,model.getExhibitionId())
                .eq(ExhibitionTask::getIsDeleted,BusinessConstant.NO)
                .eq(ExhibitionTask::getIsEnabled,BusinessConstant.YES)
                .eq(Objects.nonNull(model.getTaskId()) ,ExhibitionTask::getId,model.getTaskId())
                .orderByAsc(ExhibitionTask::getEndTime);
        Page<ExhibitionTask> page = params.buildPage();
        page = this.page(page,exhibitionTaskPageQueryQueryWrapper);
        Page<ExhibitionTaskVO> resultPage = params.buildPage();
        BeanUtils.copyProperties(page,resultPage);
        List<ExhibitionTask> records = page.getRecords();
        List<ExhibitionTaskVO> exhibitionTaskVOs = new ArrayList<>();
        for (ExhibitionTask record : records) {
            ExhibitionTaskVO exhibitionTaskVO = new ExhibitionTaskVO();
            BeanUtils.copyProperties(record,exhibitionTaskVO);
            exhibitionTaskVO.setId(record.getId());
            // 处理部门人员
            QueryWrapper<ExhibitionTaskOrg> exhibitionTaskOrgQueryWrapper = new QueryWrapper<>();
            exhibitionTaskOrgQueryWrapper.lambda()
                    .eq(ExhibitionTaskOrg::getIsDeleted,BusinessConstant.NO)
                    .eq(Objects.nonNull(record.getId()),ExhibitionTaskOrg::getTaskId,record.getId());
            List<ExhibitionTaskOrg> list = exhibitionTaskOrgService.list(exhibitionTaskOrgQueryWrapper);
            List<ExhibitionTaskOrgVO> exhibitionTasks = ConvertUtil.convertList(list, ExhibitionTaskOrgVO.class);
            exhibitionTaskVO.setExhibitionTaskOrg(exhibitionTasks);
            if(CollectionUtils.isNotEmpty(list)){
                exhibitionTaskVO.setRemindWay(list.get(0).getRemindWay());
            }

            // 处理附件
            AttachmentFileDTO attachmentFileDTO = new AttachmentFileDTO();
            attachmentFileDTO.setBusinessId(record.getId());
            attachmentFileDTO.setBusinessType(VenueBookingMoudleEnum.EXHIBITION_TASK.getCode());
            attachmentFileDTO.setIsDeleted(BusinessConstant.NO);
            attachmentFileDTO.setIsEnabled(BusinessConstant.YES);
            try{
                R<List<AttachmentFileVO>> r = attachmentFileFeign.queryAttachmentFile(attachmentFileDTO);
                List<AttachmentFileVO> data = r.getData();
                exhibitionTaskVO.setAttachmentFileList(data);
            }catch (Exception e){
                log.error(VenueBookingExceptionCode.FILE_FOUND_ERROR.getMsg(),e);
                throw BizException.wrap(VenueBookingExceptionCode.FILE_FOUND_ERROR);
            }
            // 处理展厅id
            List<ExhibitionTaskVO.ExhibitionTaskSpaceVO> spaceList = new ArrayList<>();
            for (String spaceId : record.getSpaceId().split(BusinessConstant.COMMA)) {
                Space space = spaceService.getById(Long.parseLong(spaceId));
                if(Objects.nonNull(space)){
                    spaceList.add(ExhibitionTaskVO.ExhibitionTaskSpaceVO.builder().spaceId(space.getId()).spaceName(space.getSpaceName()).build());
                }
            }
            if(CollectionUtils.isNotEmpty(spaceList)){
                exhibitionTaskVO.setSpaceName(
                        spaceList.stream().map(ExhibitionTaskVO.ExhibitionTaskSpaceVO::getSpaceName).collect(Collectors.joining(",")));
            }
            exhibitionTaskVO.setSpaceList(spaceList);
            exhibitionTaskVOs.add(exhibitionTaskVO);
        }
        resultPage.setRecords(exhibitionTaskVOs);
        return resultPage;
    }
}
